<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }

      .wrap {
        padding: 600px 0;

        p {
          opacity: 0;
          transform: translateY(30px);
          transition: opacity 0.5s, transform 0.5s;
        }

        p.visible {
          opacity: 1;
          transform: translateY(0);
        }
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <p>这是p标签1</p>
      <p>这是p标签2</p>
      <p>这是p标签3</p>
      <p>这是p标签4</p>
      <p>这是p标签5</p>
      <p>这是p标签6</p>
      <p>这是p标签7</p>
      <p>这是p标签8</p>
      <p>这是p标签9</p>
      <p>这是p标签10</p>
      <p>这是p标签11</p>
      <p>这是p标签12</p>
      <p>这是p标签13</p>
      <p>这是p标签14</p>
      <p>这是p标签15</p>
      <p>这是p标签16</p>
      <p>这是p标签17</p>
      <p>这是p标签18</p>
      <p>这是p标签19</p>
      <p>这是p标签20</p>
      <p>这是p标签21</p>
      <p>这是p标签22</p>
      <p>这是p标签23</p>
      <p>这是p标签24</p>
      <p>这是p标签25</p>
      <p>这是p标签26</p>
      <p>这是p标签27</p>
      <p>这是p标签28</p>
      <p>这是p标签29</p>
      <p>这是p标签30</p>
    </div>

    <script>
      const pEls = document.querySelectorAll('.wrap p');

      const observer = new IntersectionObserver((entries) => {
        entries.forEach(
          (entry) => {
            if (entry.isIntersecting) {
              console.log('进入可视区');

              // 进入视口添加class
              entry.target.classList.add('visible');

              // 停止观察该元素
              observer.unobserve(entry.target);
            } else {
              console.log('不在可视区内');
            }
          },
          {
            root: null,
            // 元素至少有一半进入视口时才触发回调
            threshold: 0.5,
            // 视口的可视区域扩大了50px,在每个方向上
            rootMargin: '50px',
          }
        );
      });
      pEls.forEach((pEl) => observer.observe(pEl));
    </script>
  </body>
</html>
